import json

from user_app.models import AccountInfo
from utils.common_utils import json_response
import logging
from utils import redis_client_db1

logger = logging.getLogger(__name__)
error_logger = logging.getLogger("error")


def check_login(fn):
    def wrapper(request, *args, **kwargs):
        if request.META.get('HTTP_X_API_TOKEN'):
            x_api_token = request.META.get('HTTP_X_API_TOKEN')
            user_info = redis_client_db1.hgetall(x_api_token)
            if not user_info:
                return json_response({"code": 2000, "message": "登录信息已过期，请重新登录"})
            else:
                request.session['phone'] = user_info['phone']
                request.session['password'] = user_info['password']
                request.session['account_id'] = user_info['account_id']
                return fn(request, *args, *kwargs)
        elif request.session.get('phone', ''):
            return fn(request, *args, *kwargs)
        else:
            return json_response({"code": 2000, "message": "登录信息已过期，请重新登录"})
    return wrapper


def get_token_info(fn):
    """
        未登录也可以访问接口，已登录的用户token转session
    """
    def wrapper(request, *args, **kwargs):
        if request.META.get('HTTP_X_API_TOKEN'):
            x_api_token = request.META.get('HTTP_X_API_TOKEN')
            user_info = redis_client_db1.hgetall(x_api_token)
            if not user_info:
                return json_response({"code": 2000, "message": "登录信息已过期，请重新登录"})
            else:
                request.session['phone'] = user_info['phone']
                request.session['password'] = user_info['password']
                request.session['account_id'] = user_info['account_id']
        return fn(request, *args, *kwargs)
    return wrapper


def back_role_check(fn):
    def wrapper(request, *args, **kwargs):
        if request.META.get('HTTP_X_API_TOKEN') or request.session.get('phone', ''):
            if request.META.get('HTTP_X_API_TOKEN'):
                x_api_token = request.META.get('HTTP_X_API_TOKEN')
                user_info = redis_client_db1.hgetall(x_api_token)
                if not user_info:
                    return json_response({"code": 2000, "message": "登录信息已过期，请重新登录"})
                else:
                    request.session['phone'] = user_info['phone']
                    request.session['password'] = user_info['password']
                    request.session['account_id'] = user_info['account_id']
            account = AccountInfo.objects.filter(mobile_phone=request.session['phone'], password=request.session['password']).first()
            if account:
                if account.is_superuser != 0:
                    return fn(request, *args, *kwargs)
                else:
                    return json_response({"code": 2000, "message": "权限不足"})
            else:
                return json_response({"code": 2000, "message": "登录信息已过期，请重新登录"})

        else:
            return json_response({"code": 2000, "message": "登录信息已过期，请重新登录"})
    return wrapper


def json_check(fn):
    def wrapper(request, *args, **kwargs):
        if request.method == "POST":
            try:
                json_data = json.loads(request.body)
                return fn(request, json_data, *args, *kwargs)
            except json.decoder.JSONDecodeError:
                return json_response({"code": 3000, "message": "JSON格式错误"})
            except Exception as e:
                error_logger.exception("json_check have a  error ---->%s" % e.__str__())
                return json_response({"code": 4000, "message": "服务器内部错误"})
        else:
            return json_response({"code": 3000, "message": "请求错误"})
    return wrapper
